// App.js
import React, { useState, useEffect, useRef } from 'react';
import { View, TextInput, Text, FlatList, StyleSheet, Image, TouchableOpacity, ScrollView, Platform, Modal } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
import { Audio } from 'expo-av';
import { Video, ResizeMode } from 'expo-av';
import socketService, { sendMessage, listenMessages } from '../services/socketService';
import { Ionicons } from '@expo/vector-icons';
import ChatNavBar from '@/components/ChatNavBar'
import defaultAvatar from '@/assets/images/default_avatar.png';
import { Camera, type CameraType } from 'expo-camera';
import GiftModal from '@/components/common/vip/giftmodal';
import GiftDetailModal from '@/components/common/vip/giftdetailmodal';
// import { Item } from 'react-native-paper/lib/typescript/components/Drawer/Drawer';

interface DetailProps {
  route: {
    params: {
      userId: string;
    };
  };
}
interface Gift {
  id: string;
  name: string;
  price: number;
  image: number;
}
const EMOJIS = [
  '😀', '😃', '😄', '😁', '😆', '😅', '🤣', '😂', '🙂', '🙃', '😉', '😊',
  '😇', '🥰', '😍', '🤩', '😘', '😗', '😚', '😙', '😋', '😛', '😜', '🤪',
  '😝', '🤑', '🤗', '🤭', '🤫', '🤔', '🤐', '🤨', '😐', '😑', '😶', '😏',
  '😒', '🙄', '😬', '🤥', '😌', '😔', '😪', '🤤', '😴', '😷', '🤒', '🤕',
  '🤢', '🤮', '🤧', '🥵', '🥶', '🥴', '😵', '🤯', '🤠', '🥳', '😎', '🤓',
  '🧐', '😕', '😟', '🙁', '☹️', '😮', '😯', '😲', '😳', '🥺', '😦', '😧',
  '❤️', '🧡', '💛', '💚', '💙', '💜', '🤎', '🖤', '🤍', '💯', '✨', '💫',
  '👋', '🤚', '🖐️', '✋', '🖖', '👌', '🤌', '🤏', '✌️', '🤞', '🤟', '🤘',
  '👍', '👎', '👊', '✊', '🤛', '🤜', '👏', '🙌', '👐', '🤲', '🤝', '🙏'
];

//定义用户信息
interface User {
  id?: string;
  avatar?: string;
  name?: string;
  lastMessage?: string;
  time?: string;
  unread?: number;
}
// 定义聊天消息类型
interface ChatMessage {
  id: string;
  avatar: string;
  name: string;
  lastMessage: string;
  time: string;
  unread: number;
}

type MediaType = {
  type: 'image' | 'video';
  uri: string;
};

type MessageType = {
  id: string;
  type: 'text' | 'image' | 'audio' | 'video' | 'media' | 'voice_call';
  content: string;
  media?: MediaType[];
  isSelf?: boolean;
  timestamp: number;
  showTimeHeader?: boolean;
  callStatus?: 'calling' | 'connected' | 'ended' | 'rejected';
};


// 添加通话状态类型
type CallState = {
  isInCall: boolean;
  callType: 'voice' | 'video';
  status: 'idle' | 'calling' | 'connected' | 'ended';
  duration: number;
  isMuted: boolean;
  isCameraOn: boolean;
};

const CHAT_MESSAGES: ChatMessage[] = [
  {
    id: '1',
    name: '左左',
    avatar: 'https://ts2.cn.mm.bing.net/th?id=ORMS.d06126240c548af3658f48d1981de3d9&pid=Wdp&w=268&h=140&qlt=90&c=1&rs=1&dpr=1&p=0',
    lastMessage: '今天天气真不错，要不要一起出去玩？',
    time: '3分钟前',
    unread: 2,
  },
  {
    id: '2',
    avatar: 'https://placekitten.com/101/101',
    name: '李四',
    lastMessage: '[图片]',
    time: '10分钟前',
    unread: 0,
  },
  {
    id: '3',
    avatar: 'https://ts1.cn.mm.bing.net/th?id=ORMS.2293845c570c64f281f285660f2a565c&pid=Wdp&w=268&h=140&qlt=90&c=1&rs=1&dpr=1&p=0',
    name: '王五',
    lastMessage: '好的，那就这么说定了！',
    time: '30分钟前',
    unread: 1,
  },
  {
    id: '4',
    name: '宋北',
    avatar: 'https://placekitten.com/101/101',
    lastMessage: '[语音] 10"',
    time: '1小时前',
    unread: 0,
  },
];

// 视频通话组件
const VideoCallScreen = ({
  callState,
  onUpdateCallState,
  setCameraType,
}: {
  callState: CallState;
  onUpdateCallState: (updates: Partial<CallState>) => void;
  setCameraType: React.Dispatch<React.SetStateAction<CameraType>>;
}) => (
  <View style={styles.cameraContainer}>
    <View style={[styles.fullScreenCamera, { backgroundColor: '#000' }]}>
      <View style={styles.cameraOverlay}>
        <View style={styles.cameraHeader}>
          <Text style={[styles.modalStatus, styles.whiteText]}>
            {callState.status === 'calling' ? '正在视频通话...' :
              callState.status === 'connected' ? `视频通话中 ${callState.duration}秒` :
                '视频通话结束'}
          </Text>
        </View>

        <View style={styles.cameraControls}>
          <TouchableOpacity
            style={styles.modalButton}
            onPress={() => setCameraType(current =>
              current === 'front' ? 'back' : 'front' as CameraType
            )}
          >
            <Ionicons name="camera-reverse-outline" size={24} color="white" />
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.modalButton, !callState.isCameraOn && styles.modalButtonActive]}
            onPress={() => onUpdateCallState({ isCameraOn: !callState.isCameraOn })}
          >
            <Ionicons
              name={callState.isCameraOn ? "videocam-outline" : "videocam-off-outline"}
              size={24}
              color="white"
            />
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.modalButton, callState.isMuted && styles.modalButtonActive]}
            onPress={() => onUpdateCallState({ isMuted: !callState.isMuted })}
          >
            <Ionicons
              name={callState.isMuted ? "mic-off" : "mic"}
              size={24}
              color="white"
            />
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.modalButton, styles.endCallButton]}
            onPress={() => onUpdateCallState({
              isInCall: false,
              status: 'ended',
              isCameraOn: false
            })}
          >
            <Ionicons name="call" size={24} color="white" />
          </TouchableOpacity>
        </View>
      </View>
    </View>
  </View>
);

// 音频通话组件
const AudioCallScreen = ({
  callState,
  onUpdateCallState,
}: {
  callState: CallState;
  onUpdateCallState: (updates: Partial<CallState>) => void;
}) => (
  <View style={styles.modalContent}>
    <Image source={defaultAvatar} style={styles.modalAvatar} />
    <Text style={styles.modalName}>用户名</Text>
    <Text style={styles.modalStatus}>
      {callState.status === 'calling' ? '正在语音通话...' :
        callState.status === 'connected' ? `语音通话中 ${callState.duration}秒` :
          '语音通话结束'}
    </Text>

    <View style={styles.modalControls}>
      <TouchableOpacity
        style={[styles.modalButton, callState.isMuted && styles.modalButtonActive]}
        onPress={() => onUpdateCallState({ isMuted: !callState.isMuted })}
      >
        <Ionicons
          name={callState.isMuted ? "mic-off" : "mic"}
          size={24}
          color="white"
        />
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.modalButton, styles.endCallButton]}
        onPress={() => onUpdateCallState({
          isInCall: false,
          status: 'ended',
          isMuted: false
        })}
      >
        <Ionicons name="call" size={24} color="white" />
      </TouchableOpacity>
    </View>
  </View>
);

// 修改 CallModal 组件
const CallModal = ({
  callState,
  onUpdateCallState,
  setCameraType,
}: {
  callState: CallState;
  onUpdateCallState: (updates: Partial<CallState>) => void;
  setCameraType: React.Dispatch<React.SetStateAction<CameraType>>;
}) => {
  // 根据通话类型选择显示的组件
  const renderCallScreen = () => {
    if (callState.callType === 'video') {
      return (
        <VideoCallScreen
          callState={callState}
          onUpdateCallState={onUpdateCallState}
          setCameraType={setCameraType}
        />
      );
    }
    return (
      <AudioCallScreen
        callState={callState}
        onUpdateCallState={onUpdateCallState}
      />
    );
  };

  return (
    <Modal visible={callState.isInCall} transparent>
      <View style={styles.modalContainer}>
        {renderCallScreen()}
      </View>
    </Modal>
  );
};

// 添加 AudioMessage 组件的类型和实现
type AudioMessageProps = {
  uri: string;
  isSelf: boolean;
  sound: Audio.Sound | null;
  setSound: (sound: Audio.Sound | null) => void;
};

const AudioMessage = ({ uri, isSelf, sound, setSound }: AudioMessageProps) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [duration, setDuration] = useState(0);

  const playSound = async () => {
    try {
      if (sound) {
        await sound.unloadAsync();
        setSound(null);
        setIsPlaying(false);
        return;
      }

      const { sound: newSound } = await Audio.Sound.createAsync(
        { uri },
        { shouldPlay: true },
        (status) => {
          if (!status.isLoaded) return;
          if (status.didJustFinish) {
            setIsPlaying(false);
          }
        }
      );

      setSound(newSound);
      setIsPlaying(true);

      const status = await newSound.getStatusAsync();
      if (status.isLoaded) {
        setDuration(Math.round(status.durationMillis / 1000));
      }
    } catch (error) {
      console.error('播放音频失败:', error);
      alert('此音频文件无法播放');
    }
  };

  return (
    <TouchableOpacity
      onPress={playSound}
      style={[
        styles.audioButton,
        isSelf ? styles.selfAudio : styles.otherAudio
      ]}
    >
      <Ionicons
        name={isPlaying ? "pause" : "play"}
        size={20}
        color={isSelf ? "white" : "#666"}
      />
      <View style={styles.audioInfo}>
        <Text style={{ color: isSelf ? "white" : "#666" }}>
          {isPlaying ? "正在播放" : "语音消息"}
        </Text>
        {duration > 0 && (
          <Text style={[
            styles.audioDuration,
            { color: isSelf ? "rgba(255,255,255,0.7)" : "#999" }
          ]}>
            {duration}秒
          </Text>
        )}
      </View>
    </TouchableOpacity>
  );
};

const Detail = ({ route }: DetailProps) => {
  const { userId } = route.params;
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState<MessageType[]>([]);
  const [recording, setRecording] = useState<Audio.Recording | null>(null);
  const [sound, setSound] = useState<Audio.Sound | null>(null);
  const [selectedMedia, setSelectedMedia] = useState<MediaType[]>([]);
  const [showEmojis, setShowEmojis] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [recordingDuration, setRecordingDuration] = useState(0);
  const recordingTimer = React.useRef<NodeJS.Timeout | null>(null);
  const isRecordingLocked = React.useRef(false);
  const [user, setuser] = useState<User>({})
  const [errorImages, setErrorImages] = useState<Record<string, boolean>>({})
  const [giftModalVisible, setGiftModalVisible] = useState(false);
  const [giftDetailModalVisible, setGiftDetailModalVisible] = useState(false);
  const [selectedGift, setSelectedGift] = useState(null);
  const giftData: Gift[] = [
    { id: '1', name: '玫瑰', price: 5, image: require('@/assets/images/gift/meigui.png') },
    { id: '2', name: '爱心', price: 10, image: require('@/assets/images/gift/heart-7.png') },
    { id: '3', name: '蛋糕', price: 15, image: require('@/assets/images/gift/qiaokeli.png') },
    { id: '4', name: '亲吻', price: 20, image: require('@/assets/images/gift/zuichun.png') },
    { id: '5', name: '啤酒', price: 100, image: require('@/assets/images/gift/pijiu.png') },
    { id: '6', name: '汽车', price: 200, image: require('@/assets/images/gift/paoche.png') },
    { id: '7', name: '轮船', price: 520, image: require('@/assets/images/gift/chuan.png') },
    { id: '8', name: '飞船', price: 1314, image: require('@/assets/images/gift/huojian.png') },
  ];
  const [previewMedia, setPreviewMedia] = useState<{
    type: 'image' | 'video';
    uri: string;
  } | null>(null);
  const [callState, setCallState] = useState<CallState>({
    isInCall: false,
    callType: 'voice',
    status: 'idle',
    duration: 0,
    isMuted: false,
    isCameraOn: true,
  });
  const flatListRef = useRef<FlatList>(null);
  const shouldScrollToBottom = useRef(true);
  const [cameraType, setCameraType] = useState<CameraType>('front');
  useEffect(() => {
    CHAT_MESSAGES.find(Item => {
      if (Item.id == userId) {
        setuser(Item)
      }
    })
    console.log(user);
    socketService.connect();
    return () => {
      socketService.disconnect();
    };
  }, []);

  useEffect(() => {
    const unsubscribe = listenMessages((msg: MessageType) => {
      if (!msg || typeof msg === 'string') return;

      const newMessage: MessageType = {
        id: `recv_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
        type: msg.type || 'text',
        content: msg.content || '',
        isSelf: false,
        timestamp: Date.now(),
        media: msg.media,
        showTimeHeader: false
      };

      setMessages(prev => [...prev, newMessage]);
    });

    return () => {
      unsubscribe();
    };
  }, [messages]);

  const pickMedia = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        quality: 1,
        allowsMultipleSelection: true,
        videoMaxDuration: 60,
      });
      if (!result.canceled) {
        const newMedia: MediaType[] = result.assets.map(asset => ({
          type: asset.type === 'video' ? 'video' : 'image',
          uri: asset.uri,
        }));
        console.log(newMedia);
        // 限制选择的媒体数量
        const totalMedia = selectedMedia.length + newMedia.length;
        if (totalMedia > 9) {
          console.warn('最多只能选择9个文件');
          return;
        }
        
        
        setSelectedMedia(prev => [...prev, ...newMedia]);
      }
    } catch (error) {
      console.error('选择媒体文件失败:', error);
    }
  };

  const onSendMessage = () => {
    if (message.trim() || selectedMedia.length > 0) {
      const currentTime = Date.now();
      let showTimeHeader = false;

      if (messages.length === 0) {
        showTimeHeader = true;
      } else {
        const lastMessage = messages[messages.length - 1];
        const timeDiff = currentTime - lastMessage.timestamp;
        if (timeDiff >= 5 * 60 * 1000) {
          showTimeHeader = true;
        }
      }

      const uniqueId = `msg_${currentTime}_${Math.random().toString(36).substring(2, 9)}`;

      const newMessage: MessageType = {
        id: uniqueId,
        type: selectedMedia.length > 0 ? 'media' : 'text',
        content: message,
        media: selectedMedia.length > 0 ? selectedMedia : undefined,
        isSelf: true,
        timestamp: currentTime,
        showTimeHeader
      };

      setMessages(prev => [...prev, newMessage]);
      sendMessage({
        ...newMessage,
        id: uniqueId
      });

      setMessage('');
      setSelectedMedia([]);
    }
  };

  const insertEmoji = (emoji: string) => {
    setMessage(prev => prev + emoji);
  };

  const cleanupRecording = async () => {
    try {
      if (recording) {
        await recording.stopAndUnloadAsync();
        setRecording(null);
      }
      setIsRecording(false);
      isRecordingLocked.current = false;
    } catch (error) {
      console.warn('清理录音时出错:', error);
      isRecordingLocked.current = false;
    }
  };

  const startRecording = async () => {
    try {
      if (isRecordingLocked.current) {
        console.log('录音正在处理中，请稍后再试');
        return;
      }

      if (isRecording) {
        console.log('已经在录音中');
        return;
      }

      isRecordingLocked.current = true;

      await cleanupRecording();

      const { granted } = await Audio.requestPermissionsAsync();
      if (!granted) {
        console.error('需要麦克风权限');
        isRecordingLocked.current = false;
        return;
      }

      await Audio.setAudioModeAsync({
        allowsRecordingIOS: true,
        playsInSilentModeIOS: true,
        staysActiveInBackground: true,
        shouldDuckAndroid: true,
      });

      const newRecording = new Audio.Recording();
      try {
        await newRecording.prepareToRecordAsync({
          android: {
            extension: '.m4a',
            outputFormat: Audio.AndroidOutputFormat.MPEG_4,
            audioEncoder: Audio.AndroidAudioEncoder.AAC,
            sampleRate: 44100,
            numberOfChannels: 2,
            bitRate: 128000,
          },
          ios: {
            extension: '.m4a',
            audioQuality: Audio.IOSAudioQuality.HIGH,
            sampleRate: 44100,
            numberOfChannels: 2,
            bitRate: 128000,
            linearPCMBitDepth: 16,
            linearPCMIsBigEndian: false,
            linearPCMIsFloat: false,
          },
          web: {
            mimeType: 'audio/webm',
            bitsPerSecond: 128000,
          }
        });

        await newRecording.startAsync();
        setRecording(newRecording);
        setIsRecording(true);
        setRecordingDuration(0);

        if (recordingTimer.current) {
          clearInterval(recordingTimer.current);
        }
        recordingTimer.current = setInterval(() => {
          setRecordingDuration(prev => prev + 1);
        }, 1000);

      } catch (error) {
        console.error('准备录音失败:', error);
        await cleanupRecording();
        throw error;
      }
    } catch (error) {
      console.error('录音失败:', error);
      await cleanupRecording();
    }
  };

  const stopRecording = async () => {
    if (!recording || !isRecording) {
      console.log('没有正在进行的录音');
      return;
    }

    if (recordingTimer.current) {
      clearInterval(recordingTimer.current);
      recordingTimer.current = null;
    }

    try {
      const currentRecording = recording;
      await cleanupRecording();

      if (recordingDuration < 1) {
        console.log('录音时间太短');
        return;
      }

      const uri = currentRecording.getURI();
      if (uri) {
        if (Platform.OS !== 'web') {
          const fileInfo = await FileSystem.getInfoAsync(uri);
          if (!fileInfo.exists) {
            console.error('录音文件不存在');
            return;
          }
        }

        const newMessage: MessageType = {
          id: Date.now().toString(),
          type: 'audio',
          content: uri,
          isSelf: true,
          timestamp: Date.now()
        };

        setMessages(prev => [...prev, newMessage]);
        await sendMessage({
          id: Date.now().toString(),
          type: 'audio',
          content: uri,
          timestamp: Date.now()
        });
      }
    } catch (error) {
      console.error('停止录音失败:', error);
    } finally {
      setRecordingDuration(0);
      try {
        await Audio.setAudioModeAsync({
          allowsRecordingIOS: false,
          playsInSilentModeIOS: false,
          staysActiveInBackground: false,
          shouldDuckAndroid: false,
        });
      } catch (error) {
        console.warn('重置音频模式失败:', error);
      }
    }
  };

  const removeMedia = (index: number) => {
    setSelectedMedia(prev => prev.filter((_, i) => i !== index));
  };

  useEffect(() => {
    const loadMessages = async () => {
      try {
        const history = await socketService.getMessageHistory();
        if (history && history.length > 0) {
          setMessages(history);
        }
      } catch (error) {
        console.error('加载历史消息失败:', error);
      }
    };

    loadMessages();
  }, []);

  const clearChatHistory = async () => {
    try {
      await socketService.clearHistory();
      setMessages([]);
    } catch (error) {
      console.error('清空聊天记录失败:', error);
    }
  };

  const concern = () => {
    return (
      <View>
        <Text style={{ textAlign: 'center', fontSize: 20, margin: 10 }}>消息置顶</Text>
        <Text style={{ textAlign: 'center', fontSize: 20, margin: 10 }}>添加好友</Text>
        <Text style={{ textAlign: 'center', fontSize: 20, margin: 10 }}>拉黑</Text>
        <TouchableOpacity onPress={clearChatHistory}>
          <Text style={{ textAlign: 'center', fontSize: 20, margin: 10, color: 'red' }}>
            清空聊天记录
          </Text>
        </TouchableOpacity>
      </View>
    );
  };

  const handleUpdateCallState = (updates: Partial<CallState>) => {
    setCallState(prev => {
      // 如果是结束通话，重置所有状态
      if (updates.status === 'ended') {
        return {
          ...prev,
          isInCall: false,
          status: 'ended',
          duration: 0,
          isMuted: false,
          // 只在视频通话时重置摄像头状态
          isCameraOn: prev.callType === 'video' ? false : prev.isCameraOn
        };
      }
      // 如果是开始新通话，保持对应类型的设置
      if (updates.callType) {
        return {
          ...prev,
          ...updates,
          // 视频通话默认开启摄像头，语音通话保持关闭
          isCameraOn: updates.callType === 'video'
        };
      }
      return { ...prev, ...updates };
    });
  };

  const handleVoiceCall = async () => {
    if (callState.isInCall) {
      console.log('已在通话中');
      return;
    }

    try {
      const { granted } = await Audio.requestPermissionsAsync();
      if (!granted) {
        alert('需要麦克风权限才能进行语音通话');
        return;
      }

      handleUpdateCallState({
        isInCall: true,
        callType: 'voice',
        status: 'calling',
        duration: 0,
      });
    } catch (error) {
      console.error('处理语音通话失败:', error);
    }
  };

  const handleVideoCall = async () => {
    if (callState.isInCall) return;

    try {
      const { status } = await Camera.requestCameraPermissionsAsync();
      if (status !== 'granted') {
        alert('需要相机权限才能进行视频通话');
        return;
      }

      handleUpdateCallState({
        isInCall: true,
        callType: 'video',
        status: 'calling',
        duration: 0,
      });
    } catch (error) {
      console.error('视频通话失败:', error);
    }
  };

  const renderMessage = (item: MessageType) => {
    const isSelf = item.isSelf;

    switch (item.type) {
      case 'voice_call':
        return (
          <View style={styles.callMessageContainer}>
            <View style={[
              styles.callMessage,
              isSelf ? styles.selfCall : styles.otherCall
            ]}>
              <Ionicons
                name="call"
                size={20}
                color={isSelf ? "white" : "#666"}
              />
              <Text style={[
                styles.callMessageText,
                isSelf ? styles.selfCallText : styles.otherCallText
              ]}>
                {item.content}
              </Text>
              {item.callStatus === 'calling' && (
                <View style={styles.callIndicator} />
              )}
            </View>
          </View>
        );

      case 'audio':
        return (
          <AudioMessage
            uri={item.content}
            isSelf={!!isSelf}
            sound={sound}
            setSound={setSound}
          />
        );

      case 'media':
        if (!item.media) return null;
        return (
          <View style={[
            styles.mediaMessageBubble,
            { alignSelf: isSelf ? 'flex-end' : 'flex-start' }
          ]}>
            <View style={styles.mediaContainer}>
              {item.media.map((media, index) => (
                <TouchableOpacity
                  key={index}
                  onPress={() => handleMediaPress(media)}
                  style={styles.mediaItem}
                >
                  {media.type === 'image' ? (
                    <Image
                      source={{ uri: media.uri }}
                      style={styles.mediaImage}
                    />
                  ) : (
                    <View style={styles.videoContainer}>
                      <Video
                        source={{ uri: media.uri }}
                        style={styles.video}
                        resizeMode={ResizeMode.COVER}
                        useNativeControls={false}
                        shouldPlay={false}
                        isMuted={true}
                      />
                      <View style={styles.videoIndicator}>
                        <Ionicons name="play" size={16} color="white" />
                      </View>
                    </View>
                  )}
                </TouchableOpacity>
              ))}
            </View>
          </View>
        );

      default:
        return (
          <View style={[
            styles.messageBubble,
            isSelf ? styles.selfMessage : styles.otherMessage
          ]}>
            <Text style={isSelf ? styles.selfMessageText : styles.otherMessageText}>
              {item.content}
            </Text>
          </View>
        );
    }
  };

  const formatTime = (timestamp: number) => {
    const messageDate = new Date(timestamp);
    const now = new Date();

    const localMessageTime = messageDate.getTime() - (messageDate.getTimezoneOffset() * 60000);
    const localNowTime = now.getTime() - (now.getTimezoneOffset() * 60000);

    const diffMs = localNowTime - localMessageTime;
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    const hours = messageDate.getHours().toString().padStart(2, '0');
    const minutes = messageDate.getMinutes().toString().padStart(2, '0');
    const month = messageDate.getMonth() + 1;
    const day = messageDate.getDate();
    if (diffDays === 0) {
      return `${hours}:${minutes}`;
    } else if (diffDays === 1) {
      return `昨天 ${hours}:${minutes}`;
    } else {
      return `${month}月${day}日 ${hours}:${minutes}`;
    }
  };

  const takeCameraMedia = async () => {
    try {
      const { status } = await ImagePicker.requestCameraPermissionsAsync();
      if (status !== 'granted') {
        alert('需要相机权限才能拍照或录像');
        return;
      }

      const result = await ImagePicker.launchCameraAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        quality: 1,
        videoMaxDuration: 60,
        allowsMultipleSelection: false,
        videoExportPreset: ImagePicker.VideoExportPreset.MediumQuality,
      });

      if (!result.canceled && result.assets.length > 0) {
        const asset = result.assets[0];
        const newMedia: MediaType = {
          type: asset.type === 'video' ? 'video' : 'image',
          uri: asset.uri,
        };

        // 检查媒体数量限制
        if (selectedMedia.length >= 9) {
          console.warn('最多只能选择9个文件');
          return;
        }

        setSelectedMedia(prev => [...prev, newMedia]);
      }
    } catch (error) {
      console.error('拍摄失败:', error);
    }
  };

  useEffect(() => {
    return () => {
      if (recordingTimer.current) {
        clearInterval(recordingTimer.current);
      }
      cleanupRecording();
      isRecordingLocked.current = false;
    };
  }, []);

  // 添加一个函数来处理录音按钮点击
  const handleRecordPress = async () => {
    if (isRecording) {
      await stopRecording();
    } else {
      await startRecording();
    }
  };

  const handleMediaPress = (media: { type: 'image' | 'video'; uri: string }) => {
    setPreviewMedia(media);
  };

  const MediaPreviewModal = () => {
    if (!previewMedia) return null;

    return (
      <Modal
        visible={!!previewMedia}
        transparent={true}
        onRequestClose={() => setPreviewMedia(null)}
      >
        <TouchableOpacity
          style={styles.previewModal}
          activeOpacity={1}
          onPress={() => setPreviewMedia(null)}
        >
          {previewMedia.type === 'image' ? (
            <Image
              source={{ uri: previewMedia.uri }}
              style={styles.previewModalContent}
              resizeMode="contain"
            />
          ) : (
            <Video
              source={{ uri: previewMedia.uri }}
              style={styles.previewModalContent}
              shouldPlay={true}
              useNativeControls
              resizeMode={ResizeMode.CONTAIN}
              isLooping
            />
          )}
        </TouchableOpacity>
      </Modal>
    );
  };

  // 添加时间显示的辅助函数
  const shouldShowTime = (item: MessageType, index: number) => {
    if (index === 0) return true;
    const prevMessage = messages[index - 1];
    const timeDiff = item.timestamp - prevMessage.timestamp;
    return timeDiff >= 5 * 60 * 1000; // 5分钟显示一次时间
  };

  useEffect(() => {
    const handleCallStatus = (status: string) => {
      setCallState(prev => ({ ...prev, status: status as 'idle' | 'calling' | 'connected' | 'ended' }));
    };

    socketService.on('call_status', handleCallStatus);
    return () => {
      socketService.off('call_status', handleCallStatus);
    };
  }, []);

  const handleGiftSelect = (gift) => {
    setSelectedGift(gift);
    setGiftDetailModalVisible(true);
  };

  const handleReward = (gift: Gift) => {
    console.log('打赏了礼物:', gift.name);
    
    // 创建新的礼物消息
    const giftMessage: MessageType = {
      id: `gift_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
      type: 'media',
      content: `送出了 ${gift.name}`,
      media: [{
        type: 'image',
        uri: Image.resolveAssetSource(gift.image).uri // 将本地资源转换为 URI
      }],
      isSelf: true,
      timestamp: Date.now(),
      showTimeHeader: false
    };

    // 添加到消息列表
    setMessages(prev => [...prev, giftMessage]);

    // 通过 socket 发送消息
    sendMessage({
      ...giftMessage,
      id: giftMessage.id
    });

    // 关闭礼物详情模态框
    setGiftDetailModalVisible(false);
  };

  return (
    <View style={styles.container}>
      <ChatNavBar title={user.name} customModalContent={concern} />
      <FlatList
        ref={flatListRef}
        data={messages}
        keyExtractor={item => `message_${item.id}_${item.timestamp}`}
        renderItem={({ item, index }) => (
          <View key={`message_container_${item.id}_${item.timestamp}`}>
            {shouldShowTime(item, index) && (
              <View style={styles.timeHeaderContainer}>
                <Text style={styles.timeHeaderText}>
                  {formatTime(item.timestamp)}
                </Text>
              </View>
            )}
            <View style={[
              styles.messageContainer,
              item.isSelf ? styles.selfMessageContainer : styles.otherMessageContainer
            ]}>
              {!item.isSelf && (
                <Image
                  source={errorImages[item.id] ? defaultAvatar : { uri: user.avatar }}
                  style={styles.avatar}
                  onError={() => setErrorImages(prev => ({ ...prev, [item.id]: true }))}
                />
              )}
              {renderMessage(item)}
            </View>
          </View>
        )}
        onContentSizeChange={() => {
          if (shouldScrollToBottom.current) {
            flatListRef.current?.scrollToEnd({ animated: true });
          }
        }}
      />

      {selectedMedia.length > 0 && (
        <View style={styles.mediaPreview}>
          {selectedMedia.map((media, index) => (
            <View key={`preview_${index}_${media.uri}`} style={styles.previewItem}>
              {media.type === 'image' ? (
                <Image
                  source={{ uri: media.uri }}
                  style={styles.previewImage}
                  resizeMode="cover"
                />
              ) : (
                <View>
                  <Video
                    source={{ uri: media.uri }}
                    style={styles.previewVideo}
                    shouldPlay={false}
                    resizeMode={ResizeMode.COVER}
                    isMuted={true}
                  />
                  <View style={styles.videoIndicator}>
                    <Ionicons name="videocam" size={16} color="white" />
                  </View>
                </View>
              )}
              <TouchableOpacity
                onPress={() => removeMedia(index)}
                style={styles.removeMedia}
                hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
              >
                <Ionicons name="close-circle" size={20} color="white" />
              </TouchableOpacity>
            </View>
          ))}
        </View>
      )}

      <View>
        <View style={styles.inputContainer}>
          <TouchableOpacity onPress={() => setShowEmojis(!showEmojis)} style={styles.iconButton}>
            <Ionicons name="happy-outline" size={24} color="#666" />
          </TouchableOpacity>
          <TextInput
            style={styles.input}
            value={message}
            onChangeText={setMessage}
            placeholder="输入消息"
            multiline
            maxLength={200}
          />
          <TouchableOpacity
            onPress={handleRecordPress}
            style={styles.iconButton}
          >
            <Ionicons
              name={isRecording ? "mic" : "mic-outline"}
              size={24}
              color={isRecording ? "red" : "#666"}
            />
            {isRecording && (
              <Text style={styles.recordingDuration}>
                {recordingDuration}s
              </Text>
            )}
          </TouchableOpacity>
          <TouchableOpacity onPress={onSendMessage} style={styles.iconButton}>
            <Ionicons name="send" size={24} color="#666" />
          </TouchableOpacity>
          <View style={{ flexDirection: 'row', justifyContent: 'space-evenly', width: '100%' }}>
            <TouchableOpacity onPress={pickMedia} style={styles.iconButton}>
              <Ionicons name="image" size={24} color="#666" />
            </TouchableOpacity>

            <TouchableOpacity onPress={takeCameraMedia} style={styles.iconButton}>
              <Ionicons name="camera" size={24} color="#666" />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={handleVoiceCall}
              style={[
                styles.iconButton,
                callState.isInCall && callState.callType === 'voice' && styles.activeCallButton
              ]}
              disabled={callState.isInCall}
            >
              <Ionicons
                name="call"
                size={24}
                color={callState.isInCall && callState.callType === 'voice' ? "#007AFF" : "#666"}
              />
              {callState.isInCall && <View style={styles.callIndicator} />}
            </TouchableOpacity>
            <TouchableOpacity
              onPress={handleVideoCall}
              style={[
                styles.iconButton,
                callState.isInCall && callState.callType === 'video' && styles.activeCallButton
              ]}
              disabled={callState.isInCall}
            >
              {/* 礼物选择模态框 */}
              <GiftModal
                visible={giftModalVisible}
                onClose={() => setGiftModalVisible(false)}
                onGiftSelect={handleGiftSelect}
              />

              {/* 礼物详情模态框 */}
              <GiftDetailModal
                visible={giftDetailModalVisible}
                gift={selectedGift}
                onClose={() => setGiftDetailModalVisible(false)}
                onReward={handleReward}
              />
              <Ionicons
                name="videocam"
                size={24}
                color={callState.isInCall && callState.callType === 'video' ? "#007AFF" : "#666"}
              />
              {callState.isInCall && callState.callType === 'video' && <View style={styles.callIndicator} />}
            </TouchableOpacity>
            <TouchableOpacity onPress={() => setGiftModalVisible(true)} style={styles.iconButton}>
              <Ionicons name="gift" size={24} color="#666" />
            </TouchableOpacity>
          </View>
        </View>

        {showEmojis && (
          <View style={styles.emojiContainer}>
            <View style={styles.emojiHeader}>
              <Text style={styles.emojiTitle}>表情</Text>
              <TouchableOpacity onPress={() => setShowEmojis(false)}>
                <Ionicons name="close" size={24} color="#666" />
              </TouchableOpacity>
            </View>
            <ScrollView style={styles.emojiScrollView}>
              <View style={styles.emojiGrid}>
                {EMOJIS.map((emoji, index) => (
                  <TouchableOpacity
                    key={`emoji_${emoji}_${index}`}
                    onPress={() => insertEmoji(emoji)}
                    style={styles.emojiButton}
                  >
                    <Text style={styles.emoji}>{emoji}</Text>
                  </TouchableOpacity>
                ))}
              </View>
            </ScrollView>
          </View>
        )}
      </View>
      <MediaPreviewModal />
      <CallModal
        callState={callState}
        onUpdateCallState={handleUpdateCallState}
        setCameraType={setCameraType}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  messageList: {
    flex: 1,
    padding: 8,
  },
  inputContainer: {
    width: '100%',
    flexDirection: 'row',
    flexWrap: 'wrap',
    padding: 10,
    backgroundColor: 'white',
    alignItems: 'center',
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  input: {
    flex: 1,
    maxHeight: 100, // 允许多行输入，但限制最大高度
    minHeight: 40,
    minWidth: '60%',
    borderColor: '#ddd',
    borderWidth: 1,
    borderRadius: 20,
    paddingHorizontal: 15,
    marginRight: 10,
    backgroundColor: 'white',
  },
  iconButton: {
    padding: 8,
  },
  selfContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginBottom: 10,
  },
  otherContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    marginBottom: 10,
  },
  messageBubble: {
    padding: 12,
    borderRadius: 16,
    maxWidth: '70%',
    minWidth: 40,
    flexDirection: 'row',
    alignItems: 'center',
    flexWrap: 'wrap',
  },
  selfMessage: {
    backgroundColor: '#007AFF',
    alignSelf: 'flex-end',
    marginLeft: 40,
  },
  otherMessage: {
    backgroundColor: 'white',
    alignSelf: 'flex-start',
    marginRight: 40,
  },
  messageText: {
    fontSize: 16,
  },
  messageImage: {
    width: 200,
    height: 150,
    borderRadius: 8,
    marginBottom: 5, // 如果有文字，添加间距
  },
  audioButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 8,
    paddingHorizontal: 12,
    borderRadius: 16,
    minWidth: 120,
  },
  selfAudio: {
    backgroundColor: '#007AFF',
  },
  otherAudio: {
    backgroundColor: 'white',
    borderWidth: 1,
    borderColor: '#eee',
  },
  audioInfo: {
    marginLeft: 8,
    flex: 1,
  },
  audioDuration: {
    fontSize: 12,
    marginTop: 2,
  },
  emojiTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
  },
  videoContainer: {
    width: 250,
    height: 140,
    borderRadius: 8,
    overflow: 'hidden',
    marginBottom: 5,
  },
  video: {
    width: '100%',
    height: '100%',
  },
  mediaItem: {
    marginVertical: 5,
    borderRadius: 8,
    overflow: 'hidden',
  },
  selfMessageText: {
    color: 'white',
    fontSize: 16,
    lineHeight: 20,
    flexShrink: 1,
  },
  otherMessageText: {
    color: '#333',
    fontSize: 16,
    lineHeight: 20,
    flexShrink: 1,
  },
  messageTime: {
    marginTop: 5,
    alignSelf: 'flex-end',
  },
  messageTimeText: {
    fontSize: 12,
    color: '#999',
  },
  timeHeaderContainer: {
    alignItems: 'center',
    paddingVertical: 2,
  },
  timeHeaderText: {
    fontSize: 12,
    color: '#999',
    backgroundColor: 'rgba(0,0,0,0.1)',
    paddingHorizontal: 8,
    paddingVertical: 2,
    borderRadius: 10,
    marginBottom: 4,
  },
  emojiContainer: {
    height: 300,
    backgroundColor: 'white',
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  emojiHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  emojiScrollView: {
    flex: 1,
  },
  emojiGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    padding: 10,
  },
  emojiButton: {
    width: '12.5%', // 每行8个表情
    aspectRatio: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emoji: {
    fontSize: 24,
  },
  mediaPreview: {
    padding: 10,
    backgroundColor: 'white',
    borderTopWidth: 1,
    borderTopColor: '#eee',
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  previewItem: {
    position: 'relative',
    borderRadius: 8,
    overflow: 'hidden',
  },
  previewImage: {
    width: 80,
    height: 80,
    borderRadius: 8,
  },
  previewVideo: {
    width: 80,
    height: 80,
    borderRadius: 8,
    backgroundColor: '#f0f0f0',
  },
  removeMedia: {
    position: 'absolute',
    top: 4,
    right: 4,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    borderRadius: 12,
    padding: 2,
  },
  videoIndicator: {
    position: 'absolute',
    bottom: 4,
    right: 4,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    borderRadius: 12,
    padding: 4,
  },
  mediaMessageBubble: {
    maxWidth: '70%',
    backgroundColor: 'transparent',
  },
  recordingDuration: {
    position: 'absolute',
    bottom: -15,
    right: 0,
    fontSize: 12,
    color: 'red',
  },
  mediaContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 4,
    maxWidth: 250,
    backgroundColor: 'transparent',
  },
  previewModal: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.9)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  previewModalContent: {
    width: '100%',
    height: '100%',
  },
  mediaImage: {
    width: 120,
    height: 120,
    borderRadius: 8,
  },
  callMessageContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 4,
    maxWidth: '80%',
    alignSelf: 'flex-start',
  },
  callMessage: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 12,
    borderRadius: 20,
    minWidth: 120,
    maxWidth: '100%',
  },
  selfCall: {
    backgroundColor: '#007AFF',
    alignSelf: 'flex-end',
    marginLeft: 'auto',
    paddingHorizontal: 16,
  },
  otherCall: {
    backgroundColor: '#F1F1F1',
    alignSelf: 'flex-start',
    marginRight: 'auto',
    paddingHorizontal: 16,
  },
  callMessageText: {
    marginLeft: 8,
    fontSize: 14,
    flex: 1,
    flexWrap: 'wrap',
  },
  selfCallText: {
    color: 'white',
    textAlign: 'left',
  },
  otherCallText: {
    color: '#666',
    textAlign: 'left',
  },
  callIndicator: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: '#4CD964',
    marginLeft: 8,
    flexShrink: 0,
  },
  messageContainer: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginVertical: 4,
    paddingHorizontal: 16,
    width: '100%',
  },
  selfMessageContainer: {
    justifyContent: 'flex-end',
  },
  otherMessageContainer: {
    justifyContent: 'flex-start',
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 8,
  },
  activeCallButton: {
    backgroundColor: 'rgba(0, 122, 255, 0.1)',
    borderRadius: 8,
  },
  modalContainer: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContent: {
    backgroundColor: 'rgba(0,0,0,0.8)',
    padding: 20,
    borderRadius: 16,
    alignItems: 'center',
  },
  modalAvatar: {
    width: 80,
    height: 80,
    borderRadius: 40,
    marginBottom: 16,
  },
  modalName: {
    fontSize: 20,
    color: 'white',
    marginBottom: 8,
  },
  modalStatus: {
    fontSize: 16,
    color: '#ccc',
    marginBottom: 24,
  },
  modalControls: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 20,
  },
  modalButton: {
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: 'rgba(255,255,255,0.2)',
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 8,
  },
  endCallButton: {
    backgroundColor: '#FF3B30',
    transform: [{ rotate: '135deg' }],
  },
  modalButtonActive: {
    backgroundColor: 'rgba(255,0,0,0.5)',
  },
  cameraContainer: {
    flex: 1,
    width: '100%',
  },
  camera: {
    flex: 1,
  },
  cameraOverlay: {
    flex: 1,
    backgroundColor: 'transparent',
    justifyContent: 'space-between',
  },
  cameraHeader: {
    padding: 20,
    paddingTop: Platform.OS === 'ios' ? 60 : 40,
    backgroundColor: 'rgba(0,0,0,0.3)',
  },
  cameraControls: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    padding: 20,
    paddingBottom: Platform.OS === 'ios' ? 50 : 40,
    backgroundColor: 'rgba(0,0,0,0.3)',
  },
  whiteText: {
    color: 'white',
    textAlign: 'center',
    fontSize: 18,
    fontWeight: '500',
  },
  localVideo: {
    position: 'absolute',
    top: 20,
    right: 20,
    width: 100,
    height: 150,
    backgroundColor: 'black',
    zIndex: 1,
  },
  remoteVideo: {
    flex: 1,
    backgroundColor: 'black',
  },
  fullScreenCamera: {
    flex: 1,
    width: '100%',
    height: '100%',
  },
});

export default Detail;